package com.example.hyw.szysteam.arithmetic;

import java.util.Random;

/**
 * Created by HYW on 2018/6/11.
 */

public class MyNumber {
    private int numerator;
    private int denominator;

    public MyNumber(){
    }

    public MyNumber(int numerator, int denominator){
        this.numerator=numerator;
        this.denominator=denominator;
    }

    public int getNumerator() {
        return numerator;
    }

    public void setNumerator(int numerator) {
        this.numerator = numerator;
    }

    public int getDenominator() {
        return denominator;
    }

    public void setDenominator(int denominator) {
        this.denominator = denominator;
    }

    public String toString(){
        if(denominator==1){
            return String.valueOf(numerator);
        }else if(numerator>denominator){
            int mo=numerator / denominator;
            int yu=numerator % denominator;
            return String.valueOf(mo+"`"+yu/denominator);
        }else if(numerator==0){
            return "0";
        }
        return numerator+"/"+denominator;
    }

    public MyNumber createNumber(int range){
        MyNumber number=new MyNumber();
        Random random=new Random();
        int numerator=random.nextInt(range+1);
        int denominator=random.nextInt(10)+1;
        if(random.nextInt(1)==1){
            number.setNumerator(numerator);
            number.setDenominator(denominator);
        }else{
            number.setNumerator(numerator);
            number.setDenominator(1);
        }
        number=reduction(number);
        return number;

    }

    public MyNumber reduction(MyNumber number){
        int numerator=number.getNumerator();
        int denominator=number.getDenominator();
        if(numerator==0){
            number.setDenominator(1);
            return number;
        }
        int divisor=getMaxDivisor(numerator,denominator);
        if(divisor==1){
            return number;
        }else {
            number.setNumerator(number.getNumerator() /divisor);
            number.setDenominator(number.getDenominator() / divisor);
            return number;
        }
    }

    public int getMaxDivisor(int numerator,int denominator){
        if(denominator==0){
            return numerator;
        }else {
            return getMaxDivisor(denominator,numerator % denominator);
        }
    }
}
